<?php
if(!class_exists('WP_List_Table')){
    require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );
}
class adminTableViewComponent extends WP_List_Table {

	public $tableView;
	public $search_by;
	public $callAction;
	public $config=array();
	public $bulk_action=array();
	public $search_col=array();
	public $columns=array();
	public $sortable_columns=array();
	public $rows=array();

	function __construct()
	{
		parent::__construct($this->config);
	}

	public function displayTable()
	{
		?>
		<form id="<?php echo $this->config['singular']; ?>-form" action="<?php echo $_SERVER['REQUEST_URI']; ?>" method="POST">
			<?php $this->prepare_items(); ?>
			<?php $this->search_box('Search','search-filter'); ?>
			<?php $this->display(); ?>
			<?php $this->process_bulk_action(); ?>
		</form>
		<?php
	}

	public function get_bulk_actions()
	{
		return $this->bulk_action;
	}

    public function process_bulk_action()
    {
    	if(isset($_POST[$this->config['singular']]) && !empty($_POST[$this->config['singular']])){
    		$action = $this->current_action();
    		$run = $this->callAction;
    		if(is_array($_POST[$this->config['singular']]) && method_exists($run,'runActionAdminTableView')){
    			$run->runActionAdminTableView($action,$_POST[$this->config['singular']]);
    			wp_redirect($_SERVER['REQUEST_URI']);
    			exit;
    		}
    	}
    }

	public function get_search()
	{
		if(isset($_POST['s']) && !empty($_POST['s'])){
			if(!empty($this->search_by) && is_array($this->search_col) && !empty($this->search_col)){
				array_push($this->search_col,$this->search_by);
				$where = " WHERE (";
				$search_key = "";
				foreach($this->search_col as $search){
					if(end($this->search_col)!=$search){
						$search_key.=$search." LIKE '".$_POST['s']."' OR ";
					}else{
						$search_key.=$search." LIKE '".$_POST['s']."'";
					}
				}
				$where .=$search_key.")";
			}else if(!empty($this->search_by)){
				$where = " WHERE {$this->search_by} LIKE '%".$_POST['s']."%' ";
			}else if(!empty($this->search_col) && is_array($this->search_col)){
				$where = " WHERE (";
				$search_key = "";
				foreach($this->search_col as $search){
					if(end($this->search_col)!=$search){
						$search_key.=$search." LIKE '".$_POST['s']."' OR ";
					}else{
						$search_key.=$search." LIKE '".$_POST['s']."'";
					}
				}
				$where .=$search_key.")";
			}
			return $where;
		}
	}

	public function get_columns()
	{
		return array_merge(array('cb' => '<input type="checkbox" />'),$this->columns);
	}

	public function get_sortable_columns()
	{
		return $this->sortable_columns;
	}

	public function formatItem($data,$type)
	{
		switch($type){
			case 'string':
				return $data;
				break;
			case 'email':
				return "<a href='javascript:void(0)' data-email='".$data."' data-template='' onClick='izwebz.core.support.createEmail(this);'>Send Email</a>";
				break;
			case 'url':
				return "<a target='_blank' href='".$data."'>Connected</a>";
				break;
			case 'img':
				return "<img src='".$data."'/>";
				break;
			case 'date':
				return date("H:i:s d/m/Y",strtotime($data));
				break;
		}
	}

	public function prepare_items()
	{
		if(!empty($this->tableView)){
			global $wpdb,$_wp_column_headers;
			$screen = get_current_screen();
			$query = "SELECT * FROM ".$this->tableView;
			$orderby = !empty($_GET["orderby"]) ? mysql_real_escape_string($_GET["orderby"]) : 'ASC';
		    $order = !empty($_GET["order"]) ? mysql_real_escape_string($_GET["order"]) : '';
		    $query.= $this->get_search();
		    if(!empty($orderby) && !empty($order)){ $query.=' ORDER BY '.$orderby.' '.$order; }
		    $totalitems = $wpdb->query($query);
		    $perpage = 2;
		    $paged = !empty($_GET["paged"]) ? mysql_real_escape_string($_GET["paged"]) : '';
		    if(empty($paged) || !is_numeric($paged) || $paged<=0 ){ $paged=1; }
		    $totalpages = ceil($totalitems/$perpage);
		    if(!empty($paged) && !empty($perpage)){
			    $offset=($paged-1)*$perpage;
	    		$query.=' LIMIT '.(int)$offset.','.(int)$perpage;
	    	}
	    	$this->set_pagination_args( array(
				"total_items" => $totalitems,
				"total_pages" => $totalpages,
				"per_page" => $perpage,
			));
			$columns = $this->get_columns();
			$hidden = array();
			$sortable = $this->get_sortable_columns();
			$this->_column_headers = array($columns, $hidden, $sortable);
			$this->items = $wpdb->get_results($query);
		}
	}

	public function display_rows()
	{
		$records = $this->items;
		$data = "";
		list($columns,$hidden) = $this->get_column_info();
		$row = $this->rows;
		if(!empty($records)){
			foreach($records as $record){
				$data.= "<tr id='user-".$record->$row['r2'][0]."' valign='middle'>";
				foreach ($columns as $column_name => $column_display_name) {
					$class = "class='$column_name column-$column_name'";
					$style = "";
					if (in_array($column_name,$hidden)) $style = ' style="display:none;"';
					$attributes = $class . $style;
					switch ($column_name) {
						case 'cb':
						$data.='<th scope="row" class="check-column">';
						$data.='<label class="screen-reader-text" for="cb-select-'.$record->$row['r2'][0].'"></label>';
						$data.='<input type="checkbox" name="'.$this->config['singular'].'[]" id="cb-select-'.$record->$row['r2'][0].'" value="'.esc_attr( $record->$row['r2'][0] ).'">';
						$data.="</th>";					
						break;
						case "c1": $data.='<td '.$attributes.'>'.$this->formatItem($record->$row['r1'][0],$row['r1'][1]).'</td>'; break;
						case "c2": $data.='<td '.$attributes.'>'.$this->formatItem($record->$row['r2'][0],$row['r2'][1]).'</td>'; break;
						case "c3": $data.='<td '.$attributes.'>'.$this->formatItem($record->$row['r3'][0],$row['r3'][1]).'</td>'; break;
						case "c4": $data.='<td '.$attributes.'>'.$this->formatItem($record->$row['r4'][0],$row['r4'][1]).'</td>'; break;
						case "c5": $data.='<td '.$attributes.'>'.$this->formatItem($record->$row['r5'][0],$row['r5'][1]).'</td>'; break;
						case "c6": $data.='<td '.$attributes.'>'.$this->formatItem($record->$row['r6'][0],$row['r6'][1]).'</td>'; break;
						case "c7": $data.='<td '.$attributes.'>'.$this->formatItem($record->$row['r7'][0],$row['r7'][1]).'</td>'; break;
						case "c8": $data.='<td '.$attributes.'>'.$this->formatItem($record->$row['r8'][0],$row['r8'][1]).'</td>'; break;
						case "c9": $data.='<td '.$attributes.'>'.$this->formatItem($record->$row['r9'][0],$row['r9'][1]).'</td>'; break;
					}
				}
				$data .="</tr>";
			}
			echo $data;
		}
	}
}